import React from 'react';
import { Eye, EyeOff, ExternalLink } from 'lucide-react';
import { useSettings } from '@/contexts/setting';
import { ConnectionTestStatus } from '@/types/setting';

/**
 * 模型设置表单组件
 * 用于配置AI模型相关参数
 */
const ModelSettingForm: React.FC = () => {
  const { 
    state, 
    updateModelSettings, 
    toggleApiKeyVisibility, 
    testConnection 
  } = useSettings();
  
  const { 
    settings, 
    showApiKey, 
    connectionTestStatus,
    connectionTestError
  } = state;

  // 处理API地址变更
  const handleApiUrlChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateModelSettings({ apiUrl: e.target.value });
  };

  // 处理API密钥变更
  const handleApiKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateModelSettings({ apiKey: e.target.value });
  };
  
  // 处理API密钥输入框点击
  const handleApiKeyFocus = () => {
    // 如果当前是隐藏状态，切换到显示状态
    if (!showApiKey) {
      toggleApiKeyVisibility();
      
      // 使用setTimeout确保DOM更新后再设置光标位置
      setTimeout(() => {
        const input = document.getElementById('apiKey') as HTMLInputElement;
        if (input) {
          // 将光标定位到文本末尾
          input.selectionStart = input.selectionEnd = input.value.length;
        }
      }, 0);
    }
  };

  // 注意：已移除模型选择变更处理函数，因为现在只使用自定义模型

  // 处理自定义模型名称变更
  const handleCustomModelChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    updateModelSettings({ model : e.target.value });
  };

  // 处理连接测试
  const handleTestConnection = async () => {
    await testConnection();
  };

  // 掩码显示API密钥
  const maskApiKey = (key: string) => {
    if (!key) return '';
    if (key.length <= 8) return '••••••••';
    return `${key.slice(0, 4)}${'•'.repeat(key.length - 8)}${key.slice(-4)}`;
  };

  // 测试按钮状态
  const isTesting = connectionTestStatus === ConnectionTestStatus.TESTING;
  const isTestDisabled = !settings.model.apiUrl || !settings.model.apiKey || isTesting;


  // 获取错误信息提示
  const getErrorHint = () => {
    if (connectionTestStatus === ConnectionTestStatus.FAILED && connectionTestError) {
      return (
        <p className="mt-2 text-sm text-red-500">
          {connectionTestError}
        </p>
      );
    }
    return null;
  };

  return (
    <div className="p-6 space-y-6">
      <h3 className="text-lg font-medium mb-4">AI模型配置</h3>
      
      {/* API地址 */}
      <div className="space-y-2">
        <label htmlFor="apiUrl" className="block text-sm font-medium">
          API地址
        </label>
        <input
          id="apiUrl"
          type="url"
          value={settings.model.apiUrl}
          onChange={handleApiUrlChange}
          className="w-full h-12 px-3 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-primary"
          placeholder="https://api.example.com/v1"
        />
        <p className="text-xs text-muted-foreground">
          输入API服务地址，支持标准OpenAI API及兼容接口
        </p>
      </div>
      
      {/* API密钥 */}
      <div className="space-y-2">
        <label htmlFor="apiKey" className="block text-sm font-medium">
          API密钥
        </label>
        <div className="relative">
          <input
            id="apiKey"
            type={showApiKey ? 'text' : 'password'}
            value={showApiKey ? settings.model.apiKey : ''}
            onChange={handleApiKeyChange}
            onFocus={handleApiKeyFocus}
            onClick={handleApiKeyFocus}
            className="w-full h-12 px-3 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-primary pr-10"
            placeholder={showApiKey ? "输入您的API密钥" : maskApiKey(settings.model.apiKey) || "点击此处编辑API密钥"}
          />
          <button
            type="button"
            onClick={toggleApiKeyVisibility}
            className="absolute right-3 top-1/2 transform -translate-y-1/2 text-muted-foreground hover:text-foreground"
            aria-label={showApiKey ? '隐藏API密钥' : '显示API密钥'}
          >
            {showApiKey ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
          </button>
        </div>
        <p className="text-xs text-muted-foreground flex items-center">
          <span>API密钥将安全存储在本地，不会发送至服务器</span>
          <a 
            href="https://docs.example.com/api-keys" 
            target="_blank" 
            rel="noopener noreferrer"
            className="ml-1 inline-flex items-center text-primary hover:underline"
          >
            <span className="text-xs">了解更多</span>
            <ExternalLink className="h-3 w-3 ml-0.5" />
          </a>
        </p>
      </div>
      
      {/* 自定义模型 */}
      <div className="space-y-2">
        <label htmlFor="customModel" className="block text-sm font-medium">
          自定义模型
        </label>
        <input
          id="customModel"
          type="text"
          value={settings.model.model || ''}
          onChange={handleCustomModelChange}
          placeholder="输入自定义模型名称"
          className="w-full h-12 px-3 rounded-md border bg-background focus:outline-none focus:ring-2 focus:ring-primary"
        />
        <p className="text-xs text-muted-foreground">
          输入要使用的自定义模型名称
        </p>
      </div>
      
      {/* 连接测试 */}
      <div className="pt-2">
        <button
          onClick={handleTestConnection}
          disabled={isTestDisabled}
          className={`
            h-12 px-4 rounded-md transition-colors
            ${isTestDisabled
              ? 'bg-zinc-200 dark:bg-zinc-700 text-zinc-500 dark:text-zinc-400 cursor-not-allowed'
              : 'bg-zinc-100 dark:bg-zinc-800 text-foreground hover:bg-zinc-200 dark:hover:bg-zinc-700'
            }
          `}
        >
          {isTesting ? '测试中...' : '测试连接'}
        </button>
        <div>
          {connectionTestStatus === ConnectionTestStatus.SUCCESS && (
            <span className="text-green-500">连接成功</span>
          )}
          {getErrorHint()}
        </div>
      </div>
    </div>
  );
};

export default ModelSettingForm;
